package com.servicelive.service;

import java.math.BigDecimal;
import java.util.Date;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.servicelive.ServiceLiveCommonService.OrderedItemDetails;
import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Customer;
import com.servicelivedb.data.Items;
import com.servicelivedb.data.Order;
import com.servicelivedb.data.OrderItems;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class DataScriptService extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public DataScriptService() {
		super(INFO);
	}

	public String executeScript(String script) {
		String result = "All script executed successfully";
		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		try {

			String[] dbScripts = script.split(";");
			db.begin();

			Session session = db.getDataServiceManager().getSession();

			for (String sql : dbScripts) {
				SQLQuery query = session.createSQLQuery(sql);
				query.executeUpdate();
			}

			db.commit();

			log(INFO, "Starting sample operation");

		} catch (Exception e) {
			db.rollback();
			log(ERROR, "The sample java service operation has failed", e);
			return e.getMessage();
			
		}
		return result;
	}

}
